import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
/**
 * EncComm.java
 * 
 * @author Ronald Brown
 *
 * This class encrypts all data being sent, and recieves and decrypts encoded data
 */
public class EncComm
{
	//arbitrary string that the program 99.9999999999999% will not create
	private static String replacement = "somethingthatitcantcreate";
	
	//sends the data string
	public static void send(PrintWriter out, Encryption enc, String data)
	{
		//encrypts data
		String[] parts;
		System.out.println("EncComm Send Initiated");
		String encryptedData = enc.encrypt(data);
		System.out.println("Full encrypted data: " + encryptedData);
		//changes any occurrences of newline to replacement
		encryptedData = encryptedData.replace("\n", replacement);
		//more ways to get rid of newlines
		parts = encryptedData.split("\n");
		encryptedData = "";
		for(int i=0; i<parts.length; i++)
			encryptedData += parts[i];
		//encryptedData = encryptedData.replaceAll("\n", replacement);
		System.out.println("replaced data: " + encryptedData);
		//sends the data
		out.println(encryptedData);
	}
	
	//method for receiving the data
	public static String recieve(BufferedReader in, Encryption dec)
	{
		System.out.println("EncComm recieve Initiated");
		String decryptedData = "";
		try {
			decryptedData = in.readLine();
			System.out.println("Raw read data: "+decryptedData);
			decryptedData = decryptedData.replace(replacement, "\n");
			//decryptedData = decryptedData.replaceAll(replacement, "\n");
			System.out.println("replaced read data: "+decryptedData);
			//sends the decrypted data back
			decryptedData = dec.decrypt(decryptedData);
			System.out.println("plain data: "+decryptedData);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return decryptedData;
	}
	
	//very similar method to above, only difference is that this takes a DataInputStream,
	//and the above method taes a bufferedreader
	public static String recieve(DataInputStream in, Encryption dec)
	{
		String decryptedData = "";
		try {
			decryptedData = in.readLine();
			decryptedData = decryptedData.replaceAll(replacement, "\n");
			decryptedData = dec.decrypt(decryptedData);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return decryptedData;
	}
}
